﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Pipes;
using System.Threading;


public struct Comm
{
    public bool esc;
    public bool esc_plus;
    public bool esc_plus9;
    public bool esc_plus8;
    public bool esc_plusA;
    public bool esc_plusF;
    public bool esc_mfb;
    public bool esc_mfe;
    public Comm(bool esc, bool esc_plus, bool esc_plus8, bool esc_plus9, bool esc_plusA, bool esc_plusF, bool esc_mfb, bool esc_mfe)
    {
        this.esc = esc;
        this.esc_plus = esc_plus;
        this.esc_plus9 = esc_plus9;
        this.esc_plus8 = esc_plus8;
        this.esc_plusA = esc_plusA;
        this.esc_plusF = esc_plusF;
        this.esc_mfb = esc_mfb;
        this.esc_mfe = esc_mfe;

    }

}

namespace ND2DX
{

    public partial class Form1 : Form
    {
        const byte PLUS9 = 0x09;
        const byte PLUS8 = 0x08;
        const byte PLUSA = 0x0A;
        const byte PLUSF = 0x0F;
        const byte ESC = 0x1b;
        const byte PLUS = 0x2b;
        const byte MFB = 0x80;
        const byte MFB1 = 0x81;
        const byte MFB2 = 0x82;
        const byte MFE = 0x83;
        const byte MFC_DAY_OPEN = 0x04;
        const byte MFC_DAY_CLOSED = 0xfb;
        const byte MFC_RECEIPT_OPEN = 0x08;
        const byte MFC_RECEIPT_CLOSED = 0xf7;
        const byte MFC_RECEIPT_TOTAL = 0x40;
        const byte MFC_RECEIPT_TOTAL_CLOSED = 0xbf;
        const byte LEN_ROW = 32;
        const byte EM_CMD_WRONG_ORDER = 0x52;

        public static NamedPipeClientStream pipeClient;
        public static Comm comm = new Comm();
        public static int last_error = 0;
        public static byte MFCSB1 = 4;
        public static byte MFCSB2 = 1;
        public static int fiscal_bons = 1;
        public static string last_get_data = "";
        public static byte[] rx = new byte[250];
        public static int count_rx = 0;
        public static byte[] last_command = new byte[2];
        public static StringBuilder bonbuffer = new StringBuilder();
        public static int depart = 0;
        public static int depart_interest = 1;
        public static string header;
        public static string namepipe;
        public static string pathbon;
        public static string pathlog;
        public static string message="Nothing";
        public static bool connect = false;
        public static string status = "";
        public static bool badreceipt = false;
        public static bool command_ja = false;
        public static string version = "V1.3";
        public static string temp_row = "";
        public static StringBuilder[] result = new StringBuilder[3];
        public static bool service = false;

        public Form1()
        {
            if (System.Diagnostics.Process.GetProcessesByName(System.Diagnostics.Process.GetCurrentProcess().ProcessName).Length > 1)
            {
                MessageBox.Show("ПРОГРАМАТА ВЕЧЕ Е СТАРТИРАНА!");
                Environment.Exit(0);              
            }
            InitializeComponent();
        }


        public static byte Int_bcd(int val)
        {
            return (byte)(((val / 10) << 4) + (val % 10));
        }

        public static void Plus8()
        {
            comm.esc_plus8 = false;
            comm.esc = false;
            comm.esc_plus = false;
            int[] pipe_wr = new int[7];
            pipe_wr[0] = ESC;
            pipe_wr[1] = 's';
            pipe_wr[2] = 0;
            pipe_wr[3] = 3;
            pipe_wr[4] = 8;
            pipe_wr[5] = 0x60;
            pipe_wr[6] = last_error;
            Write_Pipe(pipe_wr);
            //Console.WriteLine("Esc_Plus8");


        }

        public static void Plus9()
        {
            comm.esc_plus9 = false;
            comm.esc = false;
            comm.esc_plus = false;
            int len = last_get_data.Length;
            int[] pipe_wr = new int[5 + len];
            pipe_wr[0] = ESC;
            pipe_wr[1] = 's';
            pipe_wr[2] = 0;
            pipe_wr[3] = len + 1;
            pipe_wr[4] = 9;
            int i = 5;
            for (int k = 0; k < len; k++)
            {
                pipe_wr[i] = last_get_data[i];
            }


            Write_Pipe(pipe_wr);
            //Console.WriteLine("Esc_Plus9");
        }

        public static void PlusA()
        {
            comm.esc_plusA = false;
            comm.esc = false;
            comm.esc_plus = false;
            DateTime time = new DateTime();
            time = DateTime.Now;
            int[] pipe_wr = new int[72];
            pipe_wr[0] = ESC;
            pipe_wr[1] = 's';
            pipe_wr[2] = 0;
            pipe_wr[3] = 68;
            pipe_wr[4] = 0x0A;
            pipe_wr[5] = MFCSB1;
            pipe_wr[6] = MFCSB2;
            string wr = String.Format(";" + "{0}" + "{1}" + ',' + "{2}" + "{3}" + ',' + "{4}" + "{5}" + ';' + "{6}" + "{7}" + ',' + "{8}" + "{9}" + ',' + "{10}" + "{11}" + ";" + "{12,6}" + ";",
            time.Second / 10, time.Second % 10, time.Minute / 10, time.Minute % 10, time.Hour / 10, time.Hour % 10, time.Day / 10, time.Day % 10, time.Month / 10, time.Month % 10, (time.Year - 2000) / 10, (time.Year - 2000) % 10, fiscal_bons);
            time = time.AddDays(-1);
            pipe_wr[19] = Int_bcd(time.Day);
            pipe_wr[20] = Int_bcd(time.Month);
            pipe_wr[21] = Int_bcd(time.Year - 2000);
            wr = wr + String.Format("{0}" + "{1}" + ',' + "{2}" + "{3}" + ',' + "{4}" + "{5}" + ";BN00114951001263    103533691;",
            time.Day / 10, time.Day % 10, time.Month / 10, time.Month % 10, (time.Year - 2000) / 10, (time.Year - 2000) % 10);
            int i = 7;
            for (int k = 0; k < wr.Length; k++)
            {
                pipe_wr[i++] = wr[k];
            }
            Write_Pipe(pipe_wr);
            //Console.WriteLine("Esc_PlusA");

        }


        public static void PlusF()
        {
            comm.esc_plusF = false;
            comm.esc = false;
            comm.esc_plus = false;
            //Console.WriteLine("Esc_PlusF");
        }


        public static void Write_Pipe(int[] write)
        {
            //System.Threading.Thread.Sleep(500);
            foreach (int wr in write)
            {
                pipeClient.WriteByte((byte)wr);
            }

            pipeClient.Flush();
        }




        public static bool Connect_Pipe()
        {
            connect = false;
          do
            {
               // Console.Write("Attempt to connect to {0}..." + "\n", namepipe);
                // status=String.Format("Attempt to connect to {0}..." + "\n", namepipe);
              System.Threading.Thread.Sleep(1000);
                try
                {
                    pipeClient.Connect(10);
                   
                }
                catch 
                {
                    //Console.Write("Waiting for pipeling...." + "\n");
                   // MessageBox.Show(string.Format("Waiting for pipeling...." + "\n"));
                   // status = String.Format("Waiting for pipeling...." + "\n");
                    
                }
            } while (!pipeClient.IsConnected);

           
             //Console.Write("Waiting for pipeling...." + "\n");
             //status = String.Format("Pipe ok :)." + "\n");
             connect = true;
            return true;
        }

        //Save command to file
        public static bool Save_Command(string command)   
        {
            if (badreceipt) return true;
            byte[] command_byte = Encoding.Default.GetBytes(command.ToString());
            DateTime date = new DateTime();
            date = DateTime.Now;
            string filename;
            //path="C:\\rmoffice\\ftp\\in\\";
            filename = String.Format(pathbon + date.Minute + date.Second + date.Millisecond + ".b02");
            FileStream FS = new FileStream(filename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            FS.Write(command_byte, 0, command.Length);
            FS.Flush();
            FS.Close();
            return true;
        }


        public static bool Save_Log()
        {
            string filename = String.Format(pathlog + "ND2DX" + ".log");
            
            try
            {
               FileStream FS_LOG = new FileStream(filename, System.IO.FileMode.Append, System.IO.FileAccess.Write);
               FS_LOG.Write(rx, 0, count_rx);
               FS_LOG.Write(new byte[] { (byte)'\r', (byte)'\n' }, 0, 2);
               FS_LOG.Flush();
               FS_LOG.Close();
            }
            catch (Exception ex)
            {
               // MessageBox.Show(ex.GetType().ToString());
                if (ex.GetType().ToString() == "System.IO.DirectoryNotFoundException")
                {
                    MessageBox.Show("Не е намерен пътя " + pathlog + " за лог файла.");
                   
                }
                if (ex.GetType().ToString() == "System.UnauthorizedAccessException")
                {
                    MessageBox.Show("Няма права за запис в " + pathlog + " за лог файла.");
                }

                   service = false;
            }

            //FS_LOG.Write(rx, 0, count_rx);
            //FS_LOG.Write(new byte[] { (byte)'\r', (byte)'\n' }, 0, 2);
            //FS_LOG.Flush();
            //FS_LOG.Close();

            return true;
        }
        public static bool Check_Command()
        {
            if(service) Save_Log();
            byte comma = rx[0];
            byte commb = rx[1];
            last_command[0] = comma;
            last_command[1] = commb;

            if (comma == 'I')
            {
                //Console.WriteLine("I");
            }

            else if (comma == 'k' && commb == 'k')
            {
                //Console.WriteLine("kk");
            }

            else if (comma == 'k' && commb == 'l')
            {
                //Console.WriteLine("kl");
            }

            else if (comma == 'k' && commb == 'b')
            {
                //Console.WriteLine("kb");
            }

            else if (comma == 'i' && commb == 'i')
            {
                 //Cancel Receipt
                bonbuffer.Remove(0, bonbuffer.Length);
                MFCSB1 &= MFC_RECEIPT_TOTAL_CLOSED;
                MFCSB1 &= MFC_RECEIPT_CLOSED;
                last_error = 0;
                badreceipt = true;
                //Console.WriteLine("ii");
            }

            else if (comma == 'k' && commb == 'e')
            {
                //Console.WriteLine("ke");
            }

            else if (comma == 'a' && commb == 'a')
            {
                //Console.WriteLine("aa");
            }

            else if (comma == 'a' && commb == 'b')
            {
                //Console.WriteLine("ab");
                bonbuffer.Remove(0, bonbuffer.Length);
                bonbuffer.Append("117~2\r\n");
                Save_Command(bonbuffer.ToString());
                //Console.WriteLine("ab");
                return true;
            }

            else if (comma == 'a' && commb == 'c')
            {
                //Console.WriteLine("ac");
                bonbuffer.Remove(0, bonbuffer.Length);
                bonbuffer.Append("117~2\r\n");
                Save_Command(bonbuffer.ToString());
                //Console.WriteLine("ac");
                return true;
            }

            else if (comma == 'b' && commb == 'a')
            {
                //Start fiscal bon 
                //Console.WriteLine("ba");
                if ((MFCSB1 & MFC_RECEIPT_OPEN) == MFC_RECEIPT_OPEN)
                {
                    last_error = EM_CMD_WRONG_ORDER;
                    MessageBox.Show("Bon is open");
                    return false;
                }
                temp_row = "";
                badreceipt = false;
                MFCSB1 |= MFC_RECEIPT_OPEN;
                MFCSB1 &= MFC_RECEIPT_TOTAL_CLOSED;
                bonbuffer.Remove(0, bonbuffer.Length);
                bonbuffer.Append("48~1~0000~1\r\n");
                bonbuffer.Append(header);
                bonbuffer.Append("54~\r\n");
                bonbuffer.Append("54~\r\n");
                bonbuffer.Append("54~  ДАНЪЧЕН НОМЕР:   103533691\r\n");
                bonbuffer.Append("54~\r\n");
                /*
                int[] pipe_wr = new int[7];
                pipe_wr[0] = ESC;
                pipe_wr[1] = 'm';
                pipe_wr[2] = 0;
                pipe_wr[3] = 12;
                pipe_wr[4] = 1;
                pipe_wr[5] = 1;
                pipe_wr[6] = 0;
                Write_Pipe(pipe_wr);
                */
                last_error = 0;
                //Console.WriteLine("ba");
                return true;
            }

            else if (comma == 'b' && commb == 'b')
            {
                //Receipt END 
                bonbuffer.Append("56\r\n");
                MFCSB1 &= MFC_RECEIPT_TOTAL_CLOSED;
                MFCSB1 &= MFC_RECEIPT_CLOSED;
                fiscal_bons++;
                last_error = 0;
                Save_Command(bonbuffer.ToString());
                //Console.WriteLine("bb");
                return true;
            }

            else if (comma == 'd' && commb == 'a')
            {
                //Total 
                MFCSB1 |= MFC_RECEIPT_TOTAL;
                bonbuffer.Append("53~ОБЩА СУМА\r\n");
                last_error = 0;
                //Console.WriteLine("da");
                return true;
            }

            else if (comma == 'f' && commb == 'a')
            {
                //ARTICLE_SELL
                bonbuffer.Append("49~");
                string temp_fa = "";
                string rxnd = Encoding.Default.GetString(rx, 0, count_rx);
                string split = Encoding.Default.GetString(new byte[] { ESC, MFB1 }, 0, 2);
                string[] data = rxnd.Split(new string[] { (split) }, StringSplitOptions.None);
                if (data.Length < 5)
                {
                    MessageBox.Show("Error no FA-BA");
                    return false;
                }

                data[1] = CyrMik(data[1]);
                //bonbuffer.Append('~'+data[1].Substring(2, data[1].Length - 2)); //Article Name 
                temp_fa = (data[1].Substring(2, data[1].Length - 2));
                if (temp_fa.Length > 25)
                {
                    temp_fa = temp_fa.Substring(0, 25);
                }

                if (data[3].Substring(2, 1) == "1")  //Price with DDS
                {
                    //bonbuffer.Append("~~" + depart + '+');
                    temp_fa += ("~~" + depart + "~+");
                }
                else
                {
                    //bonbuffer.Append("~~" + depart_interest + '+');  //Depart for interest
                    temp_fa += ("~~" + depart_interest + "~+");
                }

                data[2] = data[2].Substring(2, data[2].Length-2);
                 decimal price = Convert.ToDecimal(data[2]); //Price
                 if (price > 100000000)
                 {
                     MessageBox.Show("Сумата за разплащане е по-голяма от 1000000");
                     return false;
                 }
                //bonbuffer.Append('~'+(price / 100).ToString() + '.' + (price % 100).ToString());
                //temp_fa += ('~' + (price / 100).ToString() + '.' + (price % 1000).ToString());
                temp_fa +=String.Format("~{0}.{1:00}",Math.Floor(price / 100),(price % 100));
                int quantity = Convert.ToInt32(data[4].Substring(2, data[4].Length - 4));
                //bonbuffer.Append('~' + (quantity / 100000).ToString() + '.' + (quantity % 100000).ToString() + "\r\n");
                temp_fa += ('~' + (quantity / 100000).ToString() + '.' + (quantity % 100000).ToString() + "\r\n");
                bonbuffer.Append(temp_fa);
                //Console.WriteLine(temp_fa);
                //Console.WriteLine("fa");
                return true;
            }

            else if (comma == 'j' && (commb == 'b' || commb == 'a'))
            {

                string rxnd = Encoding.Default.GetString(rx, 0, count_rx);
                string split = Encoding.Default.GetString(new byte[] { ESC, MFB1 }, 0, 2);
                string[] data = rxnd.Split(new string[] { (split) }, StringSplitOptions.None);

                //Console.Write(data[2]);
              if (data.Length < 3)
                {
                    MessageBox.Show("Error no JA-bc");
                    return false;
                }
                command_ja = true;
                bonbuffer.Append("54~");
                data[2] = CyrMik(data[2]);               
                //remove first 2 element command
                data[2] = data[2].Substring(2, data[2].Length-2);
                //remove last 2 element end of command
                data[2] = data[2].Substring(0, data[2].Length - 2);
                int len = data[2].Length;
                if (len > LEN_ROW)
                    {
                        
                        if (temp_row != "")
                        {
                            //Check First letter is Big  in next row
                            if (data[2][0] >= 0x0410 && data[2][0] <= 0x042f)
                            {
                                //Big Letter
                                bonbuffer.Append(temp_row + "\r\n");
                                //New line
                                bonbuffer.Append("54~");

                            }
                            else
                            {
                                //Small letter
                                //bonbuffer.Append(temp_row);
                                data[2] = temp_row + " " + data[2];
                            }

                            temp_row = "";
                        } 

                        IList<string> split_ja = data[2].Split(' ');                      
                        int i = 0;
                        //Make 34 lenght's rows 1,2;
                        result[i] = new StringBuilder();
                        foreach (string item in split_ja)
                        {

                            if (item == " " || item=="") continue;
                            result[i].Append(item + " ");
                            if (result[i].Length > LEN_ROW)
                            {
                                //remove last string
                                result[i].Remove((result[i].Length - item.Length - 1), item.Length);
                                 i++;
                                result[i] = new StringBuilder();
                                result[i].Append(item + " ");
                            }
                        }


                       

                        if (result[1]!=null && result[1].Length!=0)
                        {
                            bonbuffer.Append(result[0].ToString() + "\r\n");
                            temp_row = result[1].ToString();
                            result[1].Length = 0;
                            return true;
                        }

                       bonbuffer.Append(result[0].ToString() + "\r\n");
                        return true;
                      
                    }


                if (temp_row != "")
                {
                    bonbuffer.Append(temp_row + "\r\n");
                    //New line
                    bonbuffer.Append("54~");
                    temp_row = "";

                }
                 bonbuffer.Append(data[2] + "\r\n");
                return true;
                                          
            }



            else if (comma == 'g' && commb == 'b')
            {
                //Console.WriteLine("gb");
            }



            return true;
        }

        private static bool Read_Ini_File()
        {
            string path = "nd2dx.ini";
            FileStream fsRead;
            string readFile;
            try
            {
                fsRead = new FileStream(path, FileMode.Open, FileAccess.Read);
            }
            catch
            {
                MessageBox.Show("Няма nd2dx.ini файл!");
                return false;
            }

            using (StreamReader read = new StreamReader(fsRead, Encoding.Default))
            {
                readFile = read.ReadToEnd();

            }

            if (readFile.Length == 0)
            {
               // Console.WriteLine("Init file is empty");
                MessageBox.Show("nd2dx.ini файла е празен!");
                return false;
            }
            string[] splitRead;
            string[] stringseparator = new string[] { ("\r\n") };
            splitRead = readFile.Split(stringseparator, StringSplitOptions.None);
            string[] firstLine = splitRead[0].Split(' ');
            int k = 2;
            if (firstLine.Length <=3)
            {
                //Console.WriteLine("Error in ini file first line..");
                if (firstLine.Length != 3)
                {
                    MessageBox.Show("Грешка в първия ред на nd2dx.ini.");
                    return false;
                }
                else
                {
                    MessageBox.Show("Използвате стар nd2dx.ini,департамента за лихви ще бъде като основния.");
                    k = 1;
                }
            }
            namepipe = firstLine[0];
            bool err = false;
            err = Int32.TryParse(firstLine[1], out depart);
            if (!err)
            {
                MessageBox.Show(String.Format("Грешка в данните за департамента: {0}",firstLine[1]));
                return false;
            }
            //depart = Convert.ToInt16(firstLine[1]);
            err = Int32.TryParse(firstLine[k++], out depart_interest);
            if (!err)
            {
                MessageBox.Show(String.Format("Грешка в данните за департамента: {0}", firstLine[2]));
                return false;
            }

            pathbon = firstLine[k++];
            if (pathbon == " ")
            {
                MessageBox.Show("Пътя за боновете е празен!");
                return false;
            }

            //Check Directory for bons

            
            //try
            //{
            //   pathbon=Path.GetDirectoryName(pathbon);
            //}
            //catch
            //{
            //    MessageBox.Show(string.Format("Пътя за боновете {0} е невалиден!",pathbon));
            //    return false;
            //}

            if (!System.IO.Directory.Exists(pathbon))
            {
                MessageBox.Show(string.Format("Пътя за боновете {0} е невалиден!", pathbon));
                return false;
            }

            if(pathbon.Substring(pathbon.Length-1,1) != "\\" )
            {
                MessageBox.Show(string.Format("Пътя за боновете {0} е невалиден!", pathbon));
                return false;
            }



            if (firstLine.Count()==k+1)
            {
                pathlog = firstLine[k];
                if (pathlog == " ")
                {
                    MessageBox.Show("Пътя за лог файла е празен!");
                    return false;
                }
                 //Try to save some log. //Programm Started at time
                string log = String.Format("Program started at {0}", DateTime.Now);
                for (int i = 0; i < log.Length; i++)
                {
                    rx[i] = (byte)log[i];
                }
                count_rx = log.Length;
                Save_Log();
                service = true;
            }

            for (int i = 1; i < splitRead.Length - 1; i++)
            {
                header += "54~" + splitRead[i] + "\r\n";
            }


            return true;
        }

        public static string CyrMik(string val)
        {    
            val = val.Replace("--", "-");           
            byte[] input = Encoding.Default.GetBytes(val);
            byte[] mik = new byte[input.Length];
            int i = 0;
            //bool dash=false;
            foreach (byte value in input)
            {
                if (value >= 128)
                {
                    mik[i] = (byte)(value + 64);
                }
                else
                {
                    mik[i] = value;
                }



                i++;
            }
            string CyrMik = Encoding.GetEncoding(1251).GetString(mik, 0, mik.Length);
            
            return CyrMik;
        }

        //Not runnig.This done in backgroundworker.
     /*  static void MainND2DX()
        {
              
            comm.esc = false;
            byte read = 0;
            DateTime time = new DateTime();
            time = DateTime.Now;
            count_rx = 0;
            //Console.WriteLine("5.3");
            if (!Read_Ini_File())
            {
                // Console.WriteLine("No nd2dx.ini file...");
                //Console.ReadKey();
                MessageBox.Show("Can not find nd2dx.ini file. Now exit!");
                Environment.Exit(0);
            }

            //Console.WriteLine("Depart:{0}  Depart_Interest:{1}   Path={2}", depart, depart_interest, pathbon);
            message = String.Format("Depart:{0}  Depart_Interest:{1}   Path={2}", depart, depart_interest, pathbon);

            //Main
            using (pipeClient = new NamedPipeClientStream(".", namepipe, PipeDirection.InOut, PipeOptions.Asynchronous))
            {
                while (true)   //Main Programm
                {
                    //Read Byte 
                    try
                    {
                        read = (byte)pipeClient.ReadByte(); //Waiting for read byte from pipe :(...
                    }
                    catch
                    {
                        Connect_Pipe();
                        
                    }


                    if (!pipeClient.IsConnected) Connect_Pipe();

                    //Console.WriteLine(read);



                    // For mbf store to buffer while mfe 
                    if (comm.esc_mfb)
                    {
                        rx[count_rx++] = read;
                        if (count_rx > 250) count_rx = 0;
                    }


                    //Wait for Plus                            
                    //-select 8,9,a,f
                    if (comm.esc_plus)
                    {
                        if (read == PLUS8) Plus8();
                        else if (read == PLUS9) Plus9();
                        else if (read == PLUSA) PlusA();
                        else if (read == PLUSF) PlusF();
                        comm.esc_plus = false;
                        comm.esc = false;
                    }

                    //Wait for Start 
                    //-select + or mbf or mfe 

                    //Wait for 0X1b start of Seqence Set Start
                    if (comm.esc)
                    {
                        if (read == PLUS) comm.esc_plus = true;
                        else if (read == MFB)
                        {
                            comm.esc_mfb = true;
                            count_rx = 0;
                        }
                        else if (read == MFE) comm.esc_mfe = true;

                    }


                    if (comm.esc_mfe)
                    {
                        comm.esc_mfb = false;
                        comm.esc_mfe = false;
                        Check_Command();
                        count_rx = 0;

                    }


                    if (read == 0x1b) comm.esc = true;
                    else comm.esc = false;


                }





            }

        }
        */


        private void Form1_Load(object sender, EventArgs e)
        {

            this.ShowInTaskbar = false;
            this.Hide();

           //notifyIcon1.BalloonTipTitle = "ND2DX";
           // notifyIcon1.BalloonTipText = message;
           // notifyIcon1.ShowBalloonTip(1000);
            //notifyIcon1.Visible = false;
           
            

            //Thread ND2DXThread = new Thread(new ThreadStart(MainND2DX));
            //ND2DXThread.Start();
            //while (ND2DXThread.ThreadState != ThreadState.Running) ;
            backgroundWorker1.WorkerSupportsCancellation = true;
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.RunWorkerAsync();
            while (!backgroundWorker1.IsBusy) ;
            notifyIcon1.Text = "ND2DX";
            notifyIcon1.ContextMenu = new ContextMenu();
            notifyIcon1.ContextMenu.MenuItems.Add("Exit", ExitApplication);
            notifyIcon1.ContextMenu.MenuItems.Add("Data", DataApplication);
            notifyIcon1.Visible = true;
           
            //notifyIcon1.Text = message;

        }

        private void DataApplication(object sender, EventArgs e)
        {
            notifyIcon1.BalloonTipTitle = "ND2DX";
            notifyIcon1.BalloonTipText = message;
            notifyIcon1.ShowBalloonTip(1);
           
        }


        private void ExitApplication(object sender, EventArgs e)
        {
            notifyIcon1.Visible = false;
            backgroundWorker1.CancelAsync();
            backgroundWorker1 = null;
            Environment.Exit(0);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            notifyIcon1.Visible = false;
            Environment.Exit(0);
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            notifyIcon1.Visible = false;
            Environment.Exit(0);
        }

       

        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            //notifyIcon1.BalloonTipTitle = "ND2DX";
            //notifyIcon1.BalloonTipText = message;
           // textBox1.Text = status;
            if (!connect)
            {
                //notifyIcon1.Icon = new Icon(@"C:\Users\admin\Desktop\ND2DX\ND2DX\ND2DX\bin\Release\Iconbest-Helldesign-Devil-mad.ico");
                notifyIcon1.Icon = ND2DX.Properties.Resources.Iconbest_Helldesign_Devil_mad;
            }
            else
            {
                //notifyIcon1.Icon = new Icon(@"C:\Users\admin\Desktop\ND2DX\ND2DX\ND2DX\bin\Release\Dryicons-Simplistica-Accept.ico");
                notifyIcon1.Icon = ND2DX.Properties.Resources.Dryicons_Simplistica_Accept;
            }

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            comm.esc = false;
            byte read = 0;
            DateTime time = new DateTime();
            time = DateTime.Now;
            count_rx = 0;
             //Console.WriteLine("5.3");
            if (!Read_Ini_File())
            {
                // Console.WriteLine("No nd2dx.ini file...");
                //Console.ReadKey();
                notifyIcon1.Visible = false;
                Environment.Exit(0);
            }

            //Console.WriteLine("Depart:{0}  Depart_Interest:{1}   Path={2}", depart, depart_interest, pathbon);
            message = String.Format("Основен департамент: {0}  Департамент за Лихви: {1}  Path={2}  Версия: {3} ", depart, depart_interest, pathbon,version);

            //Main
            pipeClient = new NamedPipeClientStream(".", namepipe, PipeDirection.InOut, PipeOptions.Asynchronous);

                while (true)   //Main Programm
                {
                    //Read Byte 
                    try
                    {
                        read = (byte)pipeClient.ReadByte(); //Waiting for read byte from pipe :(...
                    }
                    catch
                    {
                        connect = false;
                        pipeClient.Close();
                        pipeClient = new NamedPipeClientStream(".", namepipe, PipeDirection.InOut, PipeOptions.Asynchronous);
                        worker.ReportProgress(1);
                        Connect_Pipe();
                        worker.ReportProgress(10);
                    }


                    if (!pipeClient.IsConnected)
                    {
                        connect = false;
                        pipeClient.Close();
                        pipeClient = new NamedPipeClientStream(".", namepipe, PipeDirection.InOut, PipeOptions.Asynchronous);
                        worker.ReportProgress(1);
                        Connect_Pipe();
                        worker.ReportProgress(10);
                    }

                    //Console.WriteLine(read);



                    // For mbf store to buffer while mfe 
                    if (comm.esc_mfb)
                    {
                        rx[count_rx++] = read;
                        if (count_rx > 250) count_rx = 0;
                    }


                    //Wait for Plus                            
                    //-select 8,9,a,f
                    if (comm.esc_plus)
                    {
                        if (read == PLUS8) Plus8();
                        else if (read == PLUS9) Plus9();
                        else if (read == PLUSA) PlusA();
                        else if (read == PLUSF) PlusF();
                        comm.esc_plus = false;
                        comm.esc = false;
                    }

                    //Wait for Start 
                    //-select + or mbf or mfe 

                    //Wait for 0X1b start of Seqence Set Start
                    if (comm.esc)
                    {
                        if (read == PLUS) comm.esc_plus = true;
                        else if (read == MFB)
                        {
                            comm.esc_mfb = true;
                            count_rx = 0;
                        }
                        else if (read == MFE) comm.esc_mfe = true;

                    }


                    if (comm.esc_mfe)
                    {
                        comm.esc_mfb = false;
                        comm.esc_mfe = false;
                        if (!Check_Command())
                        {
                            MessageBox.Show("Error in bon it will be erase");
                            badreceipt = true;
                            bonbuffer.Remove(0, bonbuffer.Length);
                        }
                        count_rx = 0;

                    }


                    if (read == 0x1b) comm.esc = true;
                    else comm.esc = false;


                }

            
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
           //Change Icon depend connect

            if( !connect)
            {
                //notifyIcon1.Icon = new Icon(@"C:\Users\admin\Desktop\ND2DX\ND2DX\ND2DX\bin\Release\Iconbest-Helldesign-Devil-mad.ico");
                notifyIcon1.Icon = ND2DX.Properties.Resources.Iconbest_Helldesign_Devil_mad;
            }
            else
            {
                //notifyIcon1.Icon = new Icon(@"C:\Users\admin\Desktop\ND2DX\ND2DX\ND2DX\bin\Release\Dryicons-Simplistica-Accept.ico");
                notifyIcon1.Icon = ND2DX.Properties.Resources.Dryicons_Simplistica_Accept;
            }
        }

        

    }







    






}
